import json
import time
import pymysql
from playwright.sync_api import sync_playwright

from config import db_host, db_port
import redis
import random
from playwright.async_api import async_playwright
import datetime
import asyncio




def main_fun(inst):
    storage_state_path = f'../auth/{inst}_state.json'
    with open(storage_state_path) as file:
        storage_state = json.load(file)
        origins = storage_state.get('origins')
        local_stroge_list = [item.get('localStorage') for item in origins]
        for local_stroge in local_stroge_list:
            for item in local_stroge:
                if item.get('name') == 'ACCESS_TOKEN':
                    authorization = item.get('value')
    print(f'成功读取{inst}登录信息:{authorization}')

    with sync_playwright() as p:
        browser = p.firefox.launch(headless=False)
        context = browser.new_context(base_url='https://cpquery.cponline.cnipa.gov.cn', storage_state=storage_state_path, ignore_https_errors=True)
        context.set_default_timeout(300000)
        context.set_default_navigation_timeout(300000)

        page = context.new_page()
        page.set_default_timeout(300000)
        page.set_default_navigation_timeout(300000)
        page.goto('https://cpquery.cponline.cnipa.gov.cn/detail/index?zhuanlisqh=Zy5dcVJElSjdX%252F1ZFzjT5g%253D%253D&anjianbh')
        time.sleep(10)

        headers = {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": 'Bearer ' + authorization,
            "userType": "USER_RZ_DAILIJIG"
        }

        post_data = {'zhuanlisqh': "2008102463248"}

        resp = page.request.post(
            url="https://cpquery.cponline.cnipa.gov.cn/api/view/gn/fyxx",
            headers=headers,
            data=post_data
        )
        print(resp.status)
        print(resp.json())



if __name__ == '__main__':
    main_fun("XHHG")